#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Command registry, used to extend and register new commands
"""

import importlib
import logging
import pkgutil
import inspect
from typing import Dict, Callable, Any, Optional, List, Tuple

logger = logging.getLogger(__name__)

class CommandRegistry:
    """Command registry for managing and extending commands"""
    
    def __init__(self):
        self._commands: Dict[str, Callable] = {}
        self._command_help: Dict[str, str] = {}
        self._command_setup: Dict[str, Callable] = {}
    
    def register(self, name: str, handler: Callable, help_text: str = "", 
                 setup_func: Optional[Callable] = None) -> None:
        """
        Register a command
        
        Args:
            name: command name
            handler: command handler function
            help_text: command help text
            setup_func: command setup function, called when registering subcommands
        """
        self._commands[name] = handler
        self._command_help[name] = help_text
        if setup_func:
            self._command_setup[name] = setup_func
    
    def get_command(self, name: str) -> Optional[Callable]:
        """
        Get command handler function
        
        Args:
            name: command name
        
        Returns:
            Optional[Callable]: command handler function, None if not found
        """
        return self._commands.get(name)
    
    def get_command_help(self, name: str) -> str:
        """
        Get command help text
        
        Args:
            name: command name
        
        Returns:
            str: command help text
        """
        return self._command_help.get(name, "")
    
    def setup_command(self, name: str, parser) -> None:
        """
        Set command arguments
        
        Args:
            name: command name
            parser: argument parser
        """
        setup_func = self._command_setup.get(name)
        if setup_func:
            setup_func(parser)
    
    def get_all_commands(self) -> List[Tuple[str, str]]:
        """
        Get all registered commands and their help text
        
        Returns:
            List[Tuple[str, str]]: list of (command name, help text)
        """
        return [(name, self._command_help.get(name, "")) for name in self._commands.keys()]
    
    @staticmethod
    def autodiscover(package_name: str) -> 'CommandRegistry':
        """
        Automatically discover and register commands in the specified package
        
        Args:
            package_name: package name
        
        Returns:
            CommandRegistry: registry with registered commands
        """
        registry = CommandRegistry()
        package = importlib.import_module(package_name)
        
        for _, module_name, is_pkg in pkgutil.iter_modules(package.__path__, package.__name__ + '.'):
            if not is_pkg:
                try:
                    module = importlib.import_module(module_name)
                    
                    # Find execute and setup_parser functions in module
                    if hasattr(module, 'execute'):
                        execute_func = getattr(module, 'execute')
                        setup_func = getattr(module, 'setup_parser', None)
                        
                        # Extract command name from module name
                        cmd_name = module_name.split('.')[-1]
                        
                        # Get module docstring as help text
                        help_text = module.__doc__ or ""
                        
                        # Register command
                        registry.register(cmd_name, execute_func, help_text, setup_func)
                        logger.debug(f"Automatically registered command: {cmd_name}")
                    
                except ImportError as e:
                    logger.warning(f"Failed to import module {module_name}: {e}")
        
        return registry


# Global command registry instance
registry = CommandRegistry() 